<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>人脸识别</title>
    <link rel="stylesheet" href="assets/layui/css/layui.css">
    <link rel="stylesheet" href="assets/css/face.css">
    <script src="assets/layui/jquery-3.4.1.min.js"></script>
    <script src="assets/layui/layui.all.js"></script>
    <script>
        var mediaStreamTrack = null; // 视频对象(全局)
        function openMedia() {
            var constraints = {
                video: {
                    width: 500, height: 500
                },
                audio: true
            };
            var video = document.getElementById('video');
            var promise = navigator.mediaDevices.getUserMedia(constraints);
            promise.then(function (mediaStream) {
                mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[1];
                video.srcObject = mediaStream;
                video.play();
            });
        }

        // 拍照
        function takePhoto() {
            //获得Canvas对象
            var video = document.getElementById('video');
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, 500, 500);
            // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
            var img = document.getElementById('canvas').toDataURL("image/png");
            document.getElementById('photo').src = img;
        }

        // 关闭摄像头
        function closeMedia() {
            mediaStreamTrack.stop();
        }

        //人脸检测
        function faceDetect() {
            var layer = layui.layer;
            var image = $("#photo")[0].src;
            if (image == null || image === '') {
                layer.msg("请拍照后进行人脸检测")
            } else {
                var content = image.substr("data:image/png;base64,".length);
                $.ajax({
                    type: "POST",
                    url: "detect",
                    data: {
                        faceImage: content
                    },
                    dataType: "json",
                    success: function (data) {
                        var result = data;
                        if (result['status'] && result['status'] === 200) {
                            var model = result['data'];
                            var tpl = document.getElementById("detect_info_tpl");
                            layui.laytpl(tpl.innerHTML).render(model, function (html) {
                                layer.open({
                                    type: 1,
                                    title: "人脸检测",
                                    skin: "layui-layer-lan",
                                    resize: false,
                                    content: html
                                });
                            });
                        } else {
                            layer.msg(result['message']);
                        }
                    }
                });
            }
        }
    </script>
    <style>
        .score_inner {
            position: relative;
            width: 48px;
            height: 48px;
            border-radius: 10px;
            background: linear-gradient(to top, silver, whitesmoke);
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .score_inner .score_inner_disc {
            position: absolute;
            width: 80%;
            height: 80%;
            border-radius: 50%;
            background: linear-gradient(silver, whitesmoke);
        }
    </style>
</head>
<body style="background-color: #f2f2f2">
<div class="layui-container">
    <div class="layui-row">
        <div class="layui-col-md12">
            <h2 style="text-align: center">基于AI的人脸检测和比对应用</h2>
        </div>
    </div>
    <div class="layui-tab layui-tab-brief">
        <ul id="tab" class="layui-tab-title">
            <li class="layui-this">人脸检测</li>
            <li>人脸比对</li>
        </ul>
        <div id="tab-content" class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <video id="video" width="500px" height="500px" autoplay="autoplay"></video>
                    </div>
                    <canvas id="canvas" width="500px" height="500px" style="display: none"></canvas>
                    <div class="layui-col-md6">
                        <img id="photo" src="" alt=""/>
                    </div>
                </div>
                <button class="layui-btn layui-btn-normal" onclick="openMedia()">打开摄像头</button>
                <button class="layui-btn layui-btn-normal" onclick="takePhoto()">拍照</button>
                <button class="layui-btn layui-btn-normal" onclick="closeMedia()">关闭摄像头</button>
                <button class="layui-btn layui-btn-normal" onclick="faceDetect()">人脸检测</button>
            </div>
            <div class="layui-tab-item">
                <div class="layui-row">
                    <div class="layui-col-md5">
                        <button type="button" class="layui-btn" id="btn_left">
                            <i class="layui-icon">&#xe67c;</i>上传图片一
                        </button>
                    </div>
                    <div class="layui-col-md2">
                        <button class="layui-btn layui-btn-normal" onclick="faceMatch()">人脸比对</button>
                    </div>
                    <div class="layui-col-md5">
                        <button type="button" class="layui-btn" id="btn_right">
                            <i class="layui-icon">&#xe67c;</i>上传图片二
                        </button>
                    </div>
                </div>
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <img id="left" src="" alt="" width="500px" height="500px"/>
                    </div>
                    <div class="layui-col-md6">
                        <img id="right" src="" alt="" width="500px" height="500px"/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script id="detect_info_tpl" type="text/html">
    <div id="detect_info" class="layui-card" style="width: 280px">
        <div class="layui-card-header">识别信息如下：</div>
        <div class="layui-card-body">
            <span>年龄：</span><span id="age" class="layui-text">{{d.age}}</span>
            <span>颜值：</span><span id="beauty">{{d.beauty}}</span>
            <span>表情：</span><span id="expression">{{d.expression}}</span>
            <span>脸型：</span><span id="faceShape">{{d.faceShape}}</span>
            <span>性别：</span><span id="gender">{{d.gender}}</span>
            <span>眼镜：</span><span id="glasses">{{d.glasses}}</span>
            <span>人种：</span><span id="race">{{d.race}}</span>
        </div>
    </div>
</script>
<script>
    //处理文件上传和比对
    var upload = layui.upload;
    upload.render({
        elem: '#btn_left',
        url: 'upload',
        accept: "images",
        acceptMime: "image/jpg,image/png",
        auto: true,
        field: "faceImage",
        size: 1024,
        done: function (res, index, upload) { //上传后的回调
            var result = res;
            if (result['status'] && result['status'] === 200) {
                var model = result['data'];
                var image = $("#left")[0];
                image.src = model;
                image.alt = model.substr(model.indexOf("?id=") + 4);
            } else {
                layer.msg(result['message']);
            }
        },
        error: function (index, upload) {
            layui.layer.msg("上传失败，稍后重试");
        }
    });

    upload.render({
        elem: '#btn_right',
        url: 'upload',
        accept: "images",
        acceptMime: "image/*",
        auto: true,
        field: "faceImage",
        size: 1024,
        done: function (res, index, upload) { //上传后的回调
            var result = res;
            if (result['status'] && result['status'] === 200) {
                var model = result['data'];
                var image = $("#right")[0];
                image.src = model;
                image.alt = model.substr(model.indexOf("?id=") + 4);
            } else {
                layer.msg(result['message']);
            }
        },
        error: function (index, upload) {
            layui.layer.msg("上传失败，稍后重试");
        }
    });

    //人脸比对
    function faceMatch() {
        var layer = layui.layer;
        var left = $("#left")[0].alt;
        if (left == null || left === '') {
            layer.msg("请上传图片一");
            return
        }
        var right = $("#right")[0].alt;
        if (right == null || right === '') {
            layer.msg("请上传图片二");
            return
        }
        $.ajax({
            type: "GET",
            url: "match?left=" + left + "&right=" + right,
            dataType: "json",
            success: function (data) {
                var result = data;
                if (result['status'] && result['status'] === 200) {
                    var model = result['data'];
                    layui.layer.msg("人脸比对分数：" + model + " 分");
                } else {
                    layer.msg(result['message']);
                }
            }
        });
    }
</script>
</html>